//
//  COCallPraiseController.swift
//  CocoProject
//
//  Created by Vill on 2023/11/15.
//

import UIKit

class COCallPraiseController: COBaseController {
    
    var anchorModel = DGChatUserInfoModel()   // 主播个人信息
    var callTime  : String!  //通话时长，单位s
    var callId  : String!   //通话记录id，扣费提交的id
    
    lazy var praiseTitle: UILabel = {
        let praise = UILabel()
        praise.text = "How do you feel ?"
        praise.textAlignment = .center
        praise.textColor = .white
        praise.font = UIFont.pingfangFont(ofSize: PTW(25), weight: .semibold)
        return praise
    }()
    
    lazy var containView: UIView = {
        let con = UIView()
        con.backgroundColor = .white
        return con
    }()
    
    lazy var iconImg: UIImageView = {
        let icon = UIImageView(frame: CGRectMake((SCREENWIDTH - PTW(110))/2, PTW(20), PTW(110), PTW(110)))
        icon.contentMode = .scaleAspectFill
        icon.layer.cornerRadius = PTW(55)
        icon.layer.masksToBounds = true
        return icon
    }()
    
    lazy var nameLbl: UILabel = {
        let praise = UILabel(frame: CGRectMake(0, self.iconImg.frame.maxY + PTW(5), SCREENWIDTH, PTW(25)))
        praise.textAlignment = .center
        praise.textColor = UIColor.colorWithHex("#2C255B")
        praise.font = UIFont.pingfangFont(ofSize: PTW(20), weight: .bold)
        return praise
    }()
    
    lazy var likeBtn: UIButton = {
        let lik = UIButton(frame: CGRectMake(PTW(90), self.nameLbl.frame.maxY + PTW(10), PTW(60), PTW(60)))
        lik.setImage(KImaged("coco_praise_upNormal"), for: .normal)
        lik.setImage(KImaged("coco_praise_upSelect"), for: .selected)
        lik.addTarget(self, action: #selector(likeAction), for: .touchUpInside)
        return lik
    }()
    
    lazy var unlikeBtn: UIButton = {
        let lik = UIButton(frame: CGRectMake(SCREENWIDTH - PTW(150), self.nameLbl.frame.maxY + PTW(10), PTW(60), PTW(60)))
        lik.setImage(KImaged("coco_praise_dowmNormal"), for: .normal)
        lik.setImage(KImaged("coco_praise_downSelect"), for: .selected)
        lik.addTarget(self, action: #selector(unlikeAction), for: .touchUpInside)
        return lik
    }()
    
    lazy var containScrollerView: UIScrollView = {
        let con = UIScrollView(frame: CGRectMake(0,0, SCREENWIDTH, SCREENHEIGHT - KStatusAndNavBarHeight))
        con.backgroundColor = .clear
        return con
    }()
    
    lazy var unlikeTextView:PlaceholderTextView = {
        let place = PlaceholderTextView(placeholder: "Please fill in the reason for dissatisfaction (200 limited)", placeholderColor: UIColor.colorWithHex("#7863A6",0.5), frame: .zero)
        place.backgroundColor = UIColor.colorWithHex("#F5F5F5")
        place.palceholdertextView.textColor = UIColor.white
        place.countLabel.textColor = UIColor.colorWithHex("#7863A6")
        place.isShowCountLabel = true  // 设置是否显示计算label
        place.limitWords = 100        // 限制字数
        place.isReturnHidden = true    // 是否return关闭键盘
        place.layer.cornerRadius = PTW(20)
        place.layer.masksToBounds = true
        //防止在拼音打字时抖动
        place.palceholdertextView.layoutManager.allowsNonContiguousLayout = false
        place.translatesAutoresizingMaskIntoConstraints = false
        place.palceholdertextView.returnKeyType = .send
        place.palceholdertextView.enablesReturnKeyAutomatically = true
        return place
    }()

    var resArr:[COTagsModel]?
    var chooseLikesArr:[COTagsModel]?
    var chooseUnlikesArr:[String]?
    var islike:Bool = true
    var likeTagsView: DGTezTagView?
    var unlikeTagsView:DGTezTagView?
    
    lazy var doneBtn: UIButton = {
        let lik = UIButton(type: .custom)
        lik.setTitle("Done", for: .normal)
        lik.setTitleColor(.white, for: .normal)
        lik.titleLabel?.font = UIFont.pingfangFont(ofSize: 18, weight: .bold)
        lik.layer.cornerRadius = PTW(65/2)
        lik.layer.masksToBounds = true
        lik.backgroundColor = UIColor.gradientFromColor(colors: [UIColor.colorWithHex("#7038FF").cgColor,UIColor.colorWithHex( "#FF3DE1").cgColor], direction: .Horizontal, range: PTW(225))
        lik.addTarget(self, action: #selector(doneAction), for: .touchUpInside)
        return lik
    }()
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        self.containView.clipsCorners(corners: [.topLeft,.topRight], radius: PTW(30))
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        setUpUI()
        getParseTag()
        self.likeBtn.isSelected = true
        self.islike = true
        self.likeBtn.isUserInteractionEnabled = false
        self.unlikeBtn.isUserInteractionEnabled = true
        view.addSubview(self.doneBtn)
        self.doneBtn.snp.makeConstraints { make in
            make.size.equalTo(CGSizeMake(PTW(225), PTW(65)))
            make.centerX.equalToSuperview()
            make.bottom.equalToSuperview().offset(-PTW(60))
        }
    }
    
    func setUpUI(){
        view.addSubview(self.praiseTitle)
        self.praiseTitle.snp.makeConstraints { make in
            make.height.equalTo(PTW(44))
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(statusBarHeight)
        }
        self.view.addSubview(self.containView)
        self.containView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalToSuperview().offset(KStatusAndNavBarHeight)
        }
        self.containView.addSubview(self.containScrollerView)
        self.containScrollerView.addSubview(self.iconImg)
        self.containScrollerView.addSubview(self.nameLbl)
        self.containScrollerView.addSubview(self.likeBtn)
        self.containScrollerView.addSubview(self.unlikeBtn)
        self.iconImg.sd_setUrlImage(anchorModel.profilePhoto, placeholder: KImaged("coco_icon_holder"))
        self.nameLbl.text = self.anchorModel.name
        self.containScrollerView.contentSize = CGSizeMake(SCREENWIDTH, self.unlikeBtn.frame.maxY + PTW(20))
    }
    
    func getParseTag(){
        var params = [String:Any]()
        params["id"] = anchorModel.id
        COHttpManager.request(target: COBaseApi.praseTag(param: params), modelType: COParseTagsModel.self) { [weak self] code, object, success in
            if (success == true){
                self?.resArr = object?.res
                self?.setLikeViewsData()
            }
        } failureBlock: { code, msg in
        }
    }
    
    func setLikeViewsData(){
        if(self.unlikeTagsView != nil){
            self.unlikeTagsView?.removeFromSuperview()
            self.unlikeTagsView = nil
        }
        if(self.likeTagsView != nil){
            self.likeTagsView?.removeFromSuperview()
            self.likeTagsView = nil
        }
        self.unlikeTextView.removeFromSuperview()
        var showStr = [String]()
        showStr.removeAll()
        if (resArr?.count ?? 0 > 0){
            for i in 0..<resArr!.count {
                let model = resArr![i]
                showStr.append("\(model.tagsName)(\(model.hits))")
            }
            let tagViewHeight = DGTezTagView.getTotalHeightWithValuesAndWords(words: showStr, sMargin: PTW(20), HMargin: PTW(40), IMargin: PTW(12))
            self.likeTagsView = DGTezTagView(frame: CGRectMake(0,self.likeBtn.frame.maxY + PTW(20), SCREENWIDTH, tagViewHeight), tagStrings: self.resArr!, isTagModel: true)
            self.likeTagsView?.normalTextColor = UIColor.colorWithHex("#2C255B")
            self.likeTagsView?.tagHeight = PTW(40)
            self.likeTagsView?.sideMargin = PTW(20)
            self.likeTagsView?.tagInsideMargin = PTW(12)
            self.likeTagsView?.isMultiple = true
            self.likeTagsView?.alignCenter = true
            self.likeTagsView?.backgroundColor = .clear
            self.containScrollerView.addSubview(self.likeTagsView!)
            self.containScrollerView.contentSize = CGSizeMake(SCREENWIDTH, (self.likeTagsView?.frame.maxY)! + PTW(100))
        }
    }
    
    func setDisLikeViewsData(){
        if(self.unlikeTagsView != nil){
            self.unlikeTagsView?.removeFromSuperview()
            self.unlikeTagsView = nil
        }
        if(self.likeTagsView != nil){
            self.likeTagsView?.removeFromSuperview()
            self.likeTagsView = nil
        }
        self.unlikeTextView.removeFromSuperview()
        let dislikeStr = ["Poor service attitude","Insufficient professional skills","False profile","Poor communication skills","Poor network connectivity","Other"]
        let tagViewHeight = DGTezTagView.getTotalHeightWithValuesAndWords(words: dislikeStr, sMargin: PTW(5), HMargin: PTW(40), IMargin: PTW(12))
        self.unlikeTagsView = DGTezTagView(frame: CGRectMake(0,self.likeBtn.frame.maxY + PTW(20), SCREENWIDTH, tagViewHeight), strArr: dislikeStr)
        self.unlikeTagsView?.tagHeight = PTW(40)
        self.unlikeTagsView?.normalTextColor = UIColor.colorWithHex("#2C255B")
        self.unlikeTagsView?.sideMargin = PTW(5)
        self.unlikeTagsView?.tagInsideMargin = PTW(12)
        self.unlikeTagsView?.isMultiple = true
        self.unlikeTagsView?.alignCenter = true
        self.unlikeTagsView?.backgroundColor = .clear
        self.containScrollerView.addSubview(self.unlikeTagsView!)
//        self.unlikeTextView.frame = CGRectMake(PTW(20),self.likeBtn.frame.maxY + PTW(30) + tagViewHeight, windowWidth - PTW(40) , PTW(120))
        self.containScrollerView.addSubview(self.unlikeTextView)
        self.unlikeTextView.snp.makeConstraints { make in
            make.size.equalTo(CGSizeMake(SCREENWIDTH - PTW(40), PTW(120)))
            make.left.equalToSuperview().offset(PTW(20))
            make.top.equalTo(self.likeBtn.snp.bottom).offset(PTW(30) + tagViewHeight)
        }
        self.containScrollerView.contentSize = CGSizeMake(SCREENWIDTH, self.likeBtn.frame.maxY + tagViewHeight + PTW(290))
    }
    
    @objc func likeAction(sender:UIButton){
        self.islike = true
        self.likeBtn.isUserInteractionEnabled = false
        self.unlikeBtn.isUserInteractionEnabled = true
        sender.isSelected = true
        self.unlikeBtn.isSelected = false
        self.chooseLikesArr?.removeAll()
        self.chooseUnlikesArr?.removeAll()
        setLikeViewsData()
    }
    
    @objc func unlikeAction(sender:UIButton){
        self.islike = false
        self.likeBtn.isUserInteractionEnabled = true
        self.unlikeBtn.isUserInteractionEnabled = false
        sender.isSelected = true
        self.likeBtn.isSelected = false
        self.chooseLikesArr?.removeAll()
        self.chooseUnlikesArr?.removeAll()
        setDisLikeViewsData()
    }
    
    @objc func doneAction(sender:UIButton){
        if (self.islike){
            self.parsePraise(isPraise: true, remark: nil)
        }else{
            var remark = ""
            if (self.chooseUnlikesArr?.count ?? 0 > 0){
                let resultString = self.chooseUnlikesArr!.joined(separator: ",")
                remark = "\(resultString),\(self.unlikeTextView.palceholdertextView.text ?? "")"
            }
            self.parsePraise(isPraise: false, remark: remark)
        }
    }

    func parsePraise(isPraise:Bool,remark:String?){
        var params = [String:Any]()
        params["streamerId"] = anchorModel.id
        params["callId"] = callId
        params["callTime"] = callTime
        params["criticize"] = isPraise ? "1":"0"
        if (!isPraise){
            params["remark"] = remark
        }else{
            if (self.chooseLikesArr?.count ?? 0 > 0){
                params["tags"] = self.chooseLikesArr!
            }
        }
        UIToolHelper.showHUD()
        COHttpManager.request(target: COBaseApi.prasePraise(param: params), modelType: CONSObjectModel.self) { [weak self]code, object, success in
            UIToolHelper.hideHUD()
            DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: {
                self?.navigationController?.popToRootViewController(animated: true)
            })
        } failureBlock: { [weak self]code, msg in
            UIToolHelper.hideHUD()
            DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: {
                self?.navigationController?.popToRootViewController(animated: true)
            })
        }
    }
}

extension COCallPraiseController:DGTezTagViewDelegate{
    
    func responseOfClickArr(arr: [String]) {
        self.chooseUnlikesArr = arr
        print("chooseUnLikesArr ----- \(self.chooseUnlikesArr!)")
    }
    
    func responseOfModelarr(modelArr: [Any]) {
        self.chooseLikesArr?.removeAll()
        for i in 0..<modelArr.count {
            self.chooseLikesArr?.append(modelArr[i] as! COTagsModel)
        }
        print("chooseLikesArr ----- \(self.chooseLikesArr!)")
    }
}
